package com.ruoyi.web.hnsdsa.controller;

import cn.hutool.json.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.hnsdsa.domain.MemberOrg;
import com.ruoyi.web.hnsdsa.service.IMemberOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2022-02-17
 */
@RestController
@RequestMapping("/system/org")
public class MemberOrgController extends BaseController {
    @Autowired
    private IMemberOrgService memberOrgService;
    @Autowired
    private ISysUserService userService;



    /**
     * 查询会员单位、团体列表
     */
    @PreAuthorize("@ss.hasPermi('system:org:list')")
    @GetMapping("/list")
    public TableDataInfo list(MemberOrg memberOrg) {
        startPage();
//        List<MemberOrg> list = memberOrgService.selectMemberOrgList(memberOrg);
        List<MemberOrg> list = memberOrgService.selectMembersIncludeMemberList(memberOrg);
        return getDataTable(list);
    }

    /**
     * 导出会员单位、团体列表
     */
    @PreAuthorize("@ss.hasPermi('system:org:export')")
    @Log(title = "会员单位、团体", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MemberOrg memberOrg) {
        List<MemberOrg> list = memberOrgService.selectMemberOrgList(memberOrg);
        ExcelUtil<MemberOrg> util = new ExcelUtil<MemberOrg>(MemberOrg.class);
        util.exportExcel(response, list, "会员机构数据");
    }

    /**
     * 获取会员单位、团体详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:org:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(memberOrgService.getById(id));
    }

    /**
     * 新增会员单位、团体
     */
    @PreAuthorize("@ss.hasPermi('system:org:add')")
    @Log(title = "会员单位、团体", businessType = BusinessType.INSERT)
    @PostMapping

    public AjaxResult add(@RequestBody MemberOrg memberOrg) {


        SysUser user = new SysUser();
        if (null == memberOrg.getMemberOrgType()) {
            memberOrg.setMemberOrgType(3L);
        }
        if (memberOrg.getMemberOrgType() == 1) {
            user.setDeptId(201L);
        } else if (memberOrg.getMemberOrgType() == 2) {
            user.setDeptId(202L);
        } else {
            user.setDeptId(200L);
        }
        user.setUserName(memberOrg.getMemberOrgUsername());
        user.setNickName(memberOrg.getMemberOrgName());
        user.setPassword(memberOrg.getMemberOrgPassword());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userService.insertUser(user);
        memberOrg.setUserId(user.getUserId());
        return toAjax(memberOrgService.save(memberOrg));
    }

    /**
     * 修改会员单位、团体
     */
    @PreAuthorize("@ss.hasPermi('system:org:edit')")
    @Log(title = "会员单位、团体", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MemberOrg memberOrg) {
        return toAjax(memberOrgService.updateById(memberOrg));
    }

    /**
     * 删除会员单位、团体
     */
    @PreAuthorize("@ss.hasPermi('system:org:remove')")
    @Log(title = "会员单位、团体", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        Arrays.asList(ids).forEach(item -> {
            MemberOrg byId = memberOrgService.getById(item);
            userService.deleteUserById(byId.getUserId());
        });
        return toAjax(memberOrgService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 设置高级账号
     *
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:org:grow')")
    @Log(title = "会员单位、团体", businessType = BusinessType.UPDATE)
    @PutMapping("/grow/{id}")
    public AjaxResult setProxyAccount(@PathVariable Long id) {
        System.out.println("升级帐号");
        MemberOrg byId = memberOrgService.getById(id);
        byId.setIsProxyOrg(1L);
        return AjaxResult.success(memberOrgService.updateById(byId));
    }

    /**
     * 设置普通账号
     *
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:org:down')")
    @Log(title = "会员单位、团体", businessType = BusinessType.UPDATE)
    @PutMapping("/down/{id}")
    public AjaxResult setDownAccount(@PathVariable Long id) {
        System.out.println("降级");
        MemberOrg byId = memberOrgService.getById(id);
        byId.setIsProxyOrg(2L);
        return AjaxResult.success(memberOrgService.updateById(byId));

    }

    @PreAuthorize("@ss.hasPermi('system:org:pay')")
    @PutMapping("/fee/{ids}")
    public AjaxResult clickPayFee(@PathVariable Long[] ids) {
        List<MemberOrg> memberOrgs = new ArrayList<MemberOrg>(ids.length);
        for (int i = 0; i < ids.length; i++) {
            MemberOrg byId = memberOrgService.getById(ids[i]);
            memberOrgs.add(byId);
        }
        //计算过程
//            Double memberPrice=memberOrgs*;





//        String s = JSONUtil.toJsonPrettyStr(feeResult);
        JSONObject feeResult = new JSONObject();
        feeResult.put("memberOrgs", memberOrgs).put("price", 7000.0);
        return AjaxResult.success(feeResult);

    }

    @PreAuthorize("@ss.hasPermi('system:org:import')")
    @PostMapping("importMembers")
    public AjaxResult importMembers(MultipartFile file, boolean updateSupport, long orgId) throws Exception {
        System.out.println("执行上传会员");
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        String operName = getUsername();
        List<SysUser> userList = util.importExcel(file.getInputStream());
        userList.forEach(System.out::println);
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("downloadTemplate")
    public void downloadTemplate() {


    }


}
